﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaProjectgantt;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaProjectgantt;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;
using YNTK.Common.Model.NPOI;
using YNTK.Common.Configuration;
using YNTK.DataEncryption;
using YNTK.ClayObject;
using YNTK.System.Interfaces.System;

namespace YNTK.SubDev.ZyOaProjectgantt
{
    /// <summary>
    /// 项目信息服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev",Name = "ZyOaProjectgantt", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaProjectganttService : IZyOaProjectganttService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaProjectganttEntity> _zyOaProjectganttRepository;
        private readonly IBillRullService _billRuleService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaProjectganttService"/>类型的新实例
        /// </summary>
        public ZyOaProjectganttService(
            ISqlSugarRepository<ZyOaProjectganttEntity> zyOaProjectganttRepository,
            IBillRullService billRuleService,
            IUserManager userManager)
        {
            _zyOaProjectganttRepository = zyOaProjectganttRepository;            
            _db = _zyOaProjectganttRepository.Context;
            _billRuleService = billRuleService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取项目信息
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaProjectganttEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaProjectganttInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取项目信息列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ZyOaProjectganttListQueryInput input)
        {
            var sidx = input.sidx == null ? "creatorTime" : input.sidx;
            List<string> querySigningTime = input.signingTime != null ? input.signingTime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startSigningTime = querySigningTime != null ? Ext.GetDateTime(querySigningTime.First()) : null;
            DateTime? endSigningTime = querySigningTime != null ? Ext.GetDateTime(querySigningTime.Last()) : null;
            var data = await _db.Queryable<ZyOaProjectganttEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.itemType), p => p.ItemType.Equals(input.itemType))
                .WhereIF(!string.IsNullOrEmpty(input.fullName), p => p.FullName.Contains(input.fullName))
                .WhereIF(querySigningTime != null, p => p.SigningTime >= new DateTime(startSigningTime.ToDate().Year, startSigningTime.ToDate().Month, startSigningTime.ToDate().Day, 0, 0, 0))
                .WhereIF(querySigningTime != null, p => p.SigningTime <= new DateTime(endSigningTime.ToDate().Year, endSigningTime.ToDate().Month, endSigningTime.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.desPerson), p => p.DesPerson.Equals(input.desPerson))
                .Select(it=> new 
                {
                    id = it.Id,
                    itemType=it.ItemType,
                    enCode=it.EnCode,
                    fullName=it.FullName,
                    customer=it.Customer,
                    timeLimit=it.TimeLimit,
                    startTime=it.StartTime,
                    endTime=it.EndTime,
                    signingTime=it.SigningTime,
                    amount=it.Amount,
                    schedule=it.Schedule,
                    stage=it.Stage,
                    desPerson=it.DesPerson,
                    managerIds=it.ManagerIds,
                    creatorTime=it.CreatorTime,
                    creatorUserId=it.CreatorUserId,
                }).MergeTable().Select<ZyOaProjectganttListOutput>().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return TkPageResult<ZyOaProjectganttListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建项目信息
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaProjectganttCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaProjectganttEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.EnCode = await _billRuleService.GetBillNumber("ZYXM");
            entity.CreatorTime = DateTime.Now;  
            entity.CreatorUserId = _userManager.UserId;
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
		/// 获取项目信息无分页列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [NonAction]
        public async Task<dynamic> GetNoPagingList([FromQuery] ZyOaProjectganttListQueryInput input)
        {
            var sidx = input.sidx == null ? "creatorTime" : input.sidx;
            List<string> querySigningTime = input.signingTime != null ? input.signingTime.Split(',').ToObeject<List<string>>() : null;
            DateTime? startSigningTime = querySigningTime != null ? Ext.GetDateTime(querySigningTime.First()) : null;
            DateTime? endSigningTime = querySigningTime != null ? Ext.GetDateTime(querySigningTime.Last()) : null;
            var data = await _db.Queryable<ZyOaProjectganttEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.itemType), p => p.ItemType.Equals(input.itemType))
                .WhereIF(!string.IsNullOrEmpty(input.fullName), p => p.FullName.Contains(input.fullName))
                .WhereIF(querySigningTime != null, p => p.SigningTime >= new DateTime(startSigningTime.ToDate().Year, startSigningTime.ToDate().Month, startSigningTime.ToDate().Day, 0, 0, 0))
                .WhereIF(querySigningTime != null, p => p.SigningTime <= new DateTime(endSigningTime.ToDate().Year, endSigningTime.ToDate().Month, endSigningTime.ToDate().Day, 23, 59, 59))
                .WhereIF(!string.IsNullOrEmpty(input.desPerson), p => p.DesPerson.Equals(input.desPerson))
                .Select(it=> new 
                {
                    id = it.Id,
                    itemType=it.ItemType,
                    enCode=it.EnCode,
                    fullName=it.FullName,
                    customer=it.Customer,
                    timeLimit=it.TimeLimit,
                    startTime=it.StartTime,
                    endTime=it.EndTime,
                    signingTime=it.SigningTime,
                    amount=it.Amount,
                    schedule=it.Schedule,
                    stage=it.Stage,
                    desPerson=it.DesPerson,
                    managerIds=it.ManagerIds,
                    creatorTime=it.CreatorTime,
                    creatorUserId=it.CreatorUserId,
                }).MergeTable().Select<ZyOaProjectganttListOutput>().OrderBy(sidx+" "+input.sort).ToListAsync();
                return data;
        }

        /// <summary>
		/// 导出项目信息
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] ZyOaProjectganttListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var exportData = new List<ZyOaProjectganttListOutput>();
            if (input.dataType == 0)
            {
                var data = Clay.Object(await this.GetList(input));
                exportData = data.Solidify<TkPageResult<ZyOaProjectganttListOutput>>().list;
            }
            else
            {
                exportData = await this.GetNoPagingList(input);
            }
            List<ParamsModel> paramList = "[{\"value\":\"项目编号\",\"field\":\"enCode\"},{\"value\":\"项目名称\",\"field\":\"fullName\"},{\"value\":\"项目金额\",\"field\":\"amount\"},{\"value\":\"签订时间\",\"field\":\"signingTime\"},{\"value\":\"项目阶段\",\"field\":\"stage\"},{\"value\":\"开始时间\",\"field\":\"startTime\"},{\"value\":\"结束时间\",\"field\":\"endTime\"},{\"value\":\"项目工期\",\"field\":\"timeLimit\"},{\"value\":\"完成进度\",\"field\":\"schedule\"},{\"value\":\"项目经理\",\"field\":\"desPerson\"},{\"value\":\"参与人员\",\"field\":\"managerIds\"},{\"value\":\"客户名称\",\"field\":\"customer\"},{\"value\":\"创建用户\",\"field\":\"creatorUserId\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},{\"value\":\"项目类型\",\"field\":\"itemType\"},]".ToList<ParamsModel>();           
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "项目信息.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            List<string> selectKeyList = input.selectKey.Split(',').ToList();
            foreach (var item in selectKeyList)
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                {
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
                }
            }
            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<ZyOaProjectganttListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            var output = new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "YNTK")
            };
            return output;
        }

        /// <summary>
        /// 更新项目信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaProjectganttUpInput input)
        {
            var entity = input.Adapt<ZyOaProjectganttEntity>();
            entity.LastModifyTime = DateTime.Now;  
            entity.LastModifyUserId = _userManager.UserId;
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除项目信息
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaProjectganttEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyOaProjectganttEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }
    }
}
